package com.difsonapps.android.joinme;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.difsonapps.android.joinme.R;
import com.difsonapps.joinme.dto.UserDTO;
import com.google.gson.GsonBuilder;

import android.accounts.Account;
import android.accounts.AccountAuthenticatorActivity;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;


public class LoginActivity extends AccountAuthenticatorActivity {

	private static final Pattern EMAIL_PATTERN = Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$", Pattern.CASE_INSENSITIVE);
	
	public final static String ARG_ACCOUNT_TYPE = "ACCOUNT_TYPE";
    public final static String ARG_AUTH_TYPE = "AUTH_TYPE";
    public final static String ARG_ACCOUNT_NAME = "ACCOUNT_NAME";
    public final static String ARG_IS_ADDING_NEW_ACCOUNT = "IS_ADDING_ACCOUNT";
    public static final String KEY_ERROR_MESSAGE = "ERR_MSG";
    public final static String PARAM_USER_PASS = "USER_PASS";
    private final int REQ_SIGNUP = 1;
    private final String TAG = this.getClass().getSimpleName();
    private AccountManager mAccountManager;
    private String mAuthTokenType;
    
    private Context context;
    private Map<String,String> passMap = new HashMap<String,String>();
    
  /** for posting authentication attempts back to UI thread */
    private final Handler mHandler = new Handler();
    private TextView mMessage;
    private String mPassword;
    private EditText mPasswordEdit;
    private EditText mUsernameEdit;

    /** Was the original caller asking for an entirely new account? */
    protected boolean mRequestNewAccount = false;

    private Thread mAuthThread;
    private String mAuthtoken;
    private String mAuthtokenType;
    private Boolean mConfirmCredentials = false;

    private static String mUsername;
    
    private String resp;
    private ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
    private String errorMsg;
    private JSONObject jsonObject;
    
    private GlobalVariables glbVar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.login_page);
        mAccountManager = AccountManager.get(getBaseContext());

        glbVar = GlobalVariables.getInstance();
        
        mAccountManager = AccountManager.get(this);
        final Intent intent = getIntent();
        mUsername = intent.getStringExtra(Constants.PARAM_USERNAME);
        mAuthtokenType = intent.getStringExtra(Constants.PARAM_AUTHTOKEN_TYPE);
        mRequestNewAccount = mUsername == null;
        mConfirmCredentials = intent.getBooleanExtra(Constants.PARAM_CONFIRMCREDENTIALS, false);       
        
        
        if( Build.VERSION.SDK_INT >= 9){
        StrictMode.ThreadPolicy policy = new
        		StrictMode.ThreadPolicy.Builder()
        		.permitAll().build();
        		StrictMode.setThreadPolicy(policy);
        }
        
        String accountName = getIntent().getStringExtra(ARG_ACCOUNT_NAME);
        Log.d("badran", TAG + ">" + accountName);
        context=this;
        mAuthTokenType = getIntent().getStringExtra(ARG_AUTH_TYPE);
        
        mUsernameEdit = (EditText) findViewById(R.id.LgEmail);
        mPasswordEdit = (EditText) findViewById(R.id.LgPassword);
        
        AutoCompleteTextView editTextLogin = (AutoCompleteTextView) findViewById(R.id.LgEmail);
        Account[] accounts = AccountManager.get(this).getAccountsByType("com.difsonapps.android.joinme");
        Set<String> emailSet = new HashSet<String>();
        for (Account account : accounts) {
        	if (EMAIL_PATTERN.matcher(account.name).matches()) {
        		emailSet.add(account.name);
        		passMap.put(account.name.toString(), mAccountManager.getPassword(account).toString());
        	}
        }
        editTextLogin.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, new ArrayList<String>(emailSet)));
        editTextLogin.setThreshold(1);
      //  if (mAuthTokenType == null)
     //       mAuthTokenType = GeneralAccount.AUTHTOKEN_TYPE_FULL_ACCESS;

        if (accountName != null) {
            ((TextView)findViewById(R.id.LgEmail)).setText(accountName);
        }
        
        
        editTextLogin.setOnItemClickListener(new OnItemClickListener() { 
	            @Override
	            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
	        	     String userName = ((TextView) findViewById(R.id.LgEmail)).getText().toString();
	        	     Log.d(userName, passMap.get(userName));

	        		TextView passView = ((TextView) findViewById(R.id.LgPassword)) ; 
	        		passView.setText(passMap.get(userName));
	            }
       });
        
    }
  
    public void handleLogin(View view) {
//      if (mRequestNewAccount) {
//          mUsername = mUsernameEdit.getText().toString();
//      }
//      mPassword = mPasswordEdit.getText().toString();
//      if (TextUtils.isEmpty(mUsername) || TextUtils.isEmpty(mPassword)) {
//          mMessage.setVisibility(View.VISIBLE);
//          mMessage.setText(getMessage());
//      } else {
//          showProgress();
//          mMessage.setVisibility(View.GONE);
//          // Start authenticating...
//              KohaAuthHandler.attemptAuth(mUsername, mPassword, mHandler,
//                  AuthenticatorActivity.this);
//      }
  	mUsername = mUsernameEdit.getText().toString();
  	mPassword = mPasswordEdit.getText().toString();
  	if (EMAIL_PATTERN.matcher(mUsername).matches()) {
  		if(mPassword.contains(" ") || mPassword.length()<6){
  	        Toast.makeText(this, "Your password must be at least 6 characters long!", Toast.LENGTH_LONG).show();
  		}
  		else{
			postParameters.add(new BasicNameValuePair("username",
					mUsername));
			postParameters.add(new BasicNameValuePair("password",
					mPassword));
			//AuthentificationThread();
			try {
				loginAuth();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

  		}
  	}
  	else
  	{
        Toast.makeText(this, "Please enter a valid email!", Toast.LENGTH_LONG).show();
  	}
  //	onAuthenticationResult("Auth_OK");
  }
    
    public void loginAuth() throws JSONException{
    	try {
    		
    		List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    		urlParameters.add(new BasicNameValuePair("email", mUsername));
    		urlParameters.add(new BasicNameValuePair("password", mPassword));
    		
 
		    String response = makeRequest("http://goovemail.com:28080/joinme/rest/login", urlParameters);
    		Log.e(TAG, " Vous etes la 3 " );
    		

//		    if( response == null)
//		    	{
//		    	Toast.makeText(this, "You entered the auth!", Toast.LENGTH_LONG).show();
//		    	
//		    	}
//		    else{
//		    	jsonObject = new JSONObject(response);
//		    }
		    
		    
//    		JSONObject dato = new JSONObject();
//            Toast.makeText(this, "You entered the auth!", Toast.LENGTH_LONG).show();
//    		String Returned;
//            HttpClient httpclient = new DefaultHttpClient();
//            HttpPost post = new HttpPost("http://goovemail.com:28080/joinme/rest/login");
//            
//            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
//            post.setEntity(formEntity);
//            
//            HttpResponse response = httpclient.execute(post);
//            HttpEntity entity = response.getEntity();
//            Returned = EntityUtils.toString(entity);
//            Toast.makeText(this, Returned, Toast.LENGTH_LONG).show();
          } catch ( Exception ioe ) {
           ioe.printStackTrace();
          }
    }
    
    public  String makeRequest(String uri, List<NameValuePair> urlParameters) {
        try {
            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(new UrlEncodedFormEntity(urlParameters));
            HttpAsyncTask ttTask = new HttpAsyncTask();
            ttTask.execute(httpPost);
           return ttTask.result;
   
        } catch (Exception e) {
        	 Log.e(TAG, e.getMessage(), e.fillInStackTrace());
        }
        return null;
    }
    
     

    public void onAuthenticationResult(String authToken) {
        // Hide the progress dialog
       // hideProgress();
       
        mAuthtoken = authToken;
        if (authToken != null) {
        	
       	 try {
 		    JSONObject obj = new JSONObject(authToken);
 		    String id_User= obj.getString("id");
 		    glbVar.setUserId(id_User);
 		} catch (Throwable t) {
 		    Log.e("My App", "Could not parse malformed JSON: \"" + authToken + "\"");
 		}      	 
	
            if (!mConfirmCredentials) {
                Log.e(TAG, "mConfirmCredentials: "+ mConfirmCredentials);
                finishLogin();
                Toast.makeText(this, "Logged in", Toast.LENGTH_LONG).show();
//                InfoActivity.loginButton.setVisibility(View.GONE);
//                InfoActivity.userLoggedInTextView.setText(getResources().getString(R.string.user_logged) + " " + mUsername);
//                InfoActivity.userLoggedInTextView.setVisibility(View.VISIBLE);
//                InfoActivity.myBooksButton.setVisibility(View.VISIBLE);
            } else {
                finishConfirmCredentials(true);
            }
        } else {
            Log.e(TAG, "onAuthenticationResult: failed to authenticate");
            //mMessage.setVisibility(View.VISIBLE);
  	        Toast.makeText(this,"Please enter a valid username/password", Toast.LENGTH_LONG).show();

               
               // Toast.makeText(this, KohaAuthHandler.auri, Toast.LENGTH_LONG).show();
            if (mRequestNewAccount) {
                // "Please enter a valid username/password.
                //mMessage
                //    .setText("Please Enter a valid userName/pass");//getText(R.string.auth_result_fail));
            } else {
                // "Please enter a valid password." (Used when the
                // account is already in the database but the password
                // doesn't work.)
                //mMessage
                //    .setText("Please enter a valid Password");//getText(R.string.auth_result_fail));
            }
        }
    }
    
    protected void finishLogin() {
        final Account account = new Account(mUsername, Constants.ACCOUNT_TYPE);

        if (mRequestNewAccount) {
            mAccountManager.addAccountExplicitly(account, mPassword, null);
            // Set contacts sync for this account.
            //ContentResolver.setSyncAutomatically(account, ContactsContract.AUTHORITY, true);
        } else {
            mAccountManager.setPassword(account, mPassword);
        }
        
        Log.d(TAG,"Password: " + mAccountManager.getPassword(account));

        
        mAccountManager.setUserData(account, Constants.AUTH_SESSION_KEY, mAuthtoken);        
       
        final Intent intent = new Intent();
        mAuthtoken = mPassword;
        intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mUsername);
        intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNT_TYPE);
        if (mAuthtokenType != null
            && mAuthtokenType.equals(Constants.AUTHTOKEN_TYPE)) {
            intent.putExtra(AccountManager.KEY_AUTHTOKEN, mAuthtoken);
        }
        setAccountAuthenticatorResult(intent.getExtras());
        setResult(RESULT_OK, intent);
        Intent i = new Intent(LoginActivity.this, ContactListActivity.class);
        SaveSharedPreference.setUserName(context,mUsername);
 		startActivity(i);
 		finish();
    }
    
    protected void finishConfirmCredentials(boolean result) {
        final Account account = new Account(mUsername, Constants.ACCOUNT_TYPE);
        mAccountManager.setPassword(account, mPassword);
        Log.d(TAG,"Password: " + mAccountManager.getPassword(account));
        final Intent intent = new Intent();
        intent.putExtra(AccountManager.KEY_BOOLEAN_RESULT, result);
        setAccountAuthenticatorResult(intent.getExtras());
        setResult(RESULT_OK, intent);
        finish();
    }
    
//
//				Intent i = new Intent(LoginActivity.this, MainActivity.class);
//				// intent.putExtra(EXTRA_MESSAGE, message);
//				startActivity(i);
//				finish();
//
//
//                // Switching to Register screen
//                Intent i = new Intent(LoginActivity.this, RegisterActivity.class);
//                startActivity(i);

        
    
	public void onLoginClick(View v){
		// submit();
//		final String userName = ((TextView) findViewById(R.id.LgEmail)).getText().toString();
//		String password = AccountUtils.getPasswordyByUserName(context, userName);
//		Toast.makeText(context, userName +" " +password, Toast.LENGTH_LONG).show();
//		
//		Account[] accounts = mAccountManager.getAccountsByType("com.difsonapps.android.joinme");
//		for (Account eachAccount : accounts) 
//		Log.d(TAG,"Password: " + mAccountManager.getPassword(eachAccount));
//		
		
      //  mUsernameEdit = (EditText) findViewById(R.id.LgEmail);
     //   mPasswordEdit = (EditText) findViewById(R.id.LgPassword);
        
        handleLogin(v);

	}
    
    public void onCreateAccountClick(View v){
      Intent i = new Intent(LoginActivity.this, RegisterActivity.class);
      startActivity(i);
  	
    }
    
    
    
    public void submit() {
    	
        final String userName = ((TextView) findViewById(R.id.LgEmail)).getText().toString();
        String password = AccountUtils.getPasswordyByUserName(context, userName);
        Toast.makeText(context, userName +" " +password, Toast.LENGTH_LONG).show();
        

    	/*

        final String userName = ((TextView) findViewById(R.id.LgEmail)).getText().toString();
        final String userPass = ((TextView) findViewById(R.id.LgPassword)).getText().toString();

        final String accountType = getIntent().getStringExtra(ARG_ACCOUNT_TYPE);

        Log.d("badran", TAG + ">" + accountType);
        
        new AsyncTask<String, Void, Intent>() {

            @Override
            protected Intent doInBackground(String... params) {

                Log.d("Badran", TAG + "> Started authenticating");

                String authtoken = null;
                Bundle data = new Bundle();
                try {
                    //authtoken = sServerAuthenticate.userSignIn(userName, userPass, mAuthTokenType);

                    data.putString(AccountManager.KEY_ACCOUNT_NAME, userName);
                    Log.d("badran", TAG + ">" + userName);
                    data.putString(AccountManager.KEY_ACCOUNT_TYPE, accountType);
                    Log.d("badran", TAG + ">"+ accountType);
                    data.putString(AccountManager.KEY_AUTHTOKEN, "authtoken");
                    data.putString(PARAM_USER_PASS, userPass);

                } catch (Exception e) {
                    data.putString(KEY_ERROR_MESSAGE, e.getMessage());
                }

                final Intent res = new Intent();
                res.putExtras(data);
                return res;
            }

            @Override
            protected void onPostExecute(Intent intent) {
                if (intent.hasExtra(KEY_ERROR_MESSAGE)) {
                    Toast.makeText(getBaseContext(), intent.getStringExtra(KEY_ERROR_MESSAGE), Toast.LENGTH_SHORT).show();
                } else {
                    finishLogin(intent);
                }
            }
        }.execute();
        */
    }

    
    private class HttpAsyncTask extends AsyncTask<HttpUriRequest, Void, String> {
    	String result= null;;
    	@Override
        protected String doInBackground(HttpUriRequest... urls) {
    		BufferedReader reader=null;
            try {
            	HttpResponse response=  new DefaultHttpClient().execute(urls[0]);
            	InputStream is= response.getEntity().getContent();
            	 if(is!=null)
            	 {
            		 reader = new BufferedReader(new InputStreamReader(is));
                     StringBuilder sb = new StringBuilder();
                     String line = null;
                     while((line = reader.readLine()) != null)
                     {
                            sb.append(line + "\n");
                     }              
                     result = sb.toString();
            	 }
            	 Log.d(TAG, "HttpAsyncTask passed succesfully");
            	  
			} catch (Exception e) {
			Log.e(TAG, e.getMessage(), e);
			}   
            
            return result;
        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
        	String id= null;
        	 Log.d(TAG,"result:" + result + "  Longeur " + result.length());
        	 
        	 try {
        		    JSONObject obj = new JSONObject(result);
        		    id= obj.getString("id");

        		} catch (Throwable t) {
        		    Log.e("My App", "Could not parse malformed JSON: \"" + result + "\"");
        		}
        	if(id!=null){
        		
   	  			onAuthenticationResult(result);
        	}
        	else 
        		onAuthenticationResult(null);
  
        	
       }
    }
    
    
}